package com.example.firstdemo.ui.screens.pages.login

import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptionsBuilder
import androidx.navigation.compose.composable
import com.example.firstdemo.ui.screens.pages.problem.problemList.navigateToProblemList
import kotlinx.serialization.Serializable

@Serializable
object Login

fun NavController.navigateToLogin(builder: NavOptionsBuilder.() -> Unit = {}) {
    navigate(Login, builder)
}

fun NavGraphBuilder.loginDestination(
    padding: PaddingValues = PaddingValues(0.dp),
    navController: NavController
) {
    composable<Login>(
        enterTransition = { fadeIn() },
        exitTransition = { fadeOut() },
        popEnterTransition = { fadeIn() },
        popExitTransition = { fadeOut() }
    ) {
        val viewModel: LoginViewModel = viewModel()
        val uiState = viewModel.uiState.collectAsStateWithLifecycle().value
        val isLoggedIn = viewModel.isLoggedIn.collectAsStateWithLifecycle().value

        LaunchedEffect(isLoggedIn) {
            if (isLoggedIn) {
                navController.navigateToProblemList {
                    popUpTo(Login) {
                        inclusive = true
                    }
                }
            }
        }
        LoginScreen(
            uiState,
            onLogin = { userName, password ->
                viewModel.login(userName, password)
            },
            onMessageConfirm = {
                viewModel.clearError()
            },
            padding = padding
        )
    }
}